package com.tgy.myplus.基础学习.Thread.线程协作;

/**
 * @author 送你一块二向箔
 * @date 2021/11/09 15:19
 */

/**
 * 测试信号灯法
 * 生产者 消费者 标志位
 */
public class TestPClighter {
    public static void main(String[] args) {
        TV tv = new TV();
        new Thread(new Player(tv)).start();
        new Thread(new Watcher(tv)).start();
    }
}

//消费者--》观众
class Watcher implements Runnable{

    TV tv;

    public Watcher(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if(i%2==0){
                this.tv.watch();
            }else {
                this.tv.watch();
            }
        }

    }
}
//生产者--》演员
class Player implements Runnable{
    TV tv ;

    public Player(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if(i%2==0){
                this.tv.play("游泳");
            }else {
                this.tv.play("踢足球");
            }
        }

    }
}

//产品节目
class TV{
    /*
    演员表演，观众等待 T
    观众观看，演员等待 F
     */
    String videos ;
    Boolean flag = true;
    public synchronized void play(String videos){
        if (!flag){
            try {
                this.wait();
                System.out.println("演员等待中");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("表演者表演了"+videos);
        //通知观看
        this.notify();
        this.videos = videos;
        this.flag = !this.flag;
    }
    public synchronized void watch(){
        if (flag){
            try {
                this.wait();
                System.out.println("观众等待中");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("观众观看了"+videos);
        //通知观看
        this.notify();
        this.flag = !this.flag;
    }
}
